<?php

    function getChildrenOptions($category, $pre = null) {
        $indent = $pre.$category->name;
        if (! empty($category->children)) {
            $children = array();

            foreach($category->children as $child) {
                $children[$child->id] = $indent.' -> '.$child->name;
                if ($childsChildren = getChildrenOptions($child, $indent.' -> ')) {
                    $children += $childsChildren;
                }
            }
            return $children;
        }
        return false;
    }

    $catOptions = array();
    foreach ($categories as $cat) {
        $catOptions[$cat->id] = $cat->name;

        if ($children = getChildrenOptions($cat)) {
            $catOptions += $children;
        }
    }

?><form action="/admin_products/save" method="post" style="width:400px" enctype="multipart/form-data">

    <? if (isset($product)): ?>
        <h1><?= $product->name ?></h1>
    <? else: ?>
        <h1>Novi proizvod</h1>
    <? endif ?>

    <?= $this->hidden(array('data', 'id'), @$product->id) ?>

    <p><?= $this->select(array('data', 'category_id'), $catOptions, array(
        'label' => 'Kategorija:',
        'empty' => false,
        'value' => @$product->category_id
    )) ?></p>

    <p><?= $this->text(array('data', 'name'), array(
        'value' => @$product->name,
        'label' => 'Naziv:'
    )) ?></p>

    <p><?= $this->image_picker(array('data', 'image'), array(
        'label'     => 'Slika:',
        'directory' => '/img/products/' . @$product->category_id,
        'value'     => @$product->image
    )) ?></p>

    <p><?= $this->text(array('data', 'price'), array(
        'label' => 'Cena:',
        'value' => (float)@$product->price,
        'class' => 'medium'
    )) ?></p>

    <p><?= $this->textarea(array('data', 'description'), array(
        'label' => 'Kratak opis:',
        'value' => @$product->description
    )) ?></p>
    
    <p><?= $this->submit('Sačuvaj') ?><? if(@$product->id): ?>
    <?= $this->link('Obriši', "/admin_products/remove/{$product->id}", array(
        'class'   => 'right input delete',
        'confirm' => 'Da li želite da obrišete proizvod?'
    )) ?><? endif ?></p>
</form><br clear="all">

<script type="text/javascript">
initRemoteLinks($('form [data-remote]'));
htmlEditor('textarea#data_description');
</script>